<script>
import axios from "axios";

export default {
    name: "JingXuanComponent",
    data() {
        return {
            //图片回显
            uploadImageList: [],
            editorOption:{},

            dialogFormVisible: false,
            dialogTitle: '',//对话框标题
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            form: {
                'id':"",
                'articlename': "",
                'articleintroduce': '',
                'teacherId': '',
                'teacherName': '',
                'tabularchart': "",  //图片
                'details': '',   //详情
                "readquantity":"",
                "collects":"",
                'typeId': '',
                'typeName': '',
                "createtime":""
            },
            tableData: [],
            formLabelWidth: '120px',

            //搜索框数据对象
            searchContent: {
                articlename:'',
                typeName:'',
                time: [],
                pageNum: 1,
                pageSize: 10,
            },
            row: {},      // 全局row 把scope.row赋给它
            allId: -1,   //全局id用来在新增和修改是做判断
            page: {
                pageSize: 10,    //默认每页显示10条
                currentPage: 1,  //默认显示第一页
                total: 0 //总条数
            },
            //咨询师
            teachers:[],
            //类型
            types:[],
            userRole:''
        }
    },
    //   页面初始化后执行
    created() {
        //获取咨询师
        this.getArticleType();
        //获取类型
        this.getTeacher();

        this.flushPage();
    },
    methods: {
        //获取咨询师
        getTeacher(){
            this.axios.get("/teacher/findAllTeacher").then(res=>{
                // console.log("teacher-----------------------")
                // console.log(res.data.data);
                this.teachers = res.data.data;
            })
        },

        //获取类型
        getArticleType(){
            this.axios.get("/articleType/findAllArticleType").then(res=>{
                // console.log("articleType--------------------")
                // console.log(res.data.data);
                this.types = res.data.data;
                console.log(this.types)
            })
        },

        save() {
            //新增
            if (this.allId === -1){
                this.dialogFormVisible = false;
                this.axios.post("/article/addArticle",{
                    id:"",
                    articlename: this.form.articlename,
                    articleintroduce: this.form.articleintroduce,
                    teacherId: this.form.teacherId,
                    tabularchart: this.form.tabularchart,  //图片
                    details: this.form.details,   //详情
                    readquantity:"",
                    collects:"",
                    typeId: this.form.typeId,
                    createtime: this.formatDateTime(new Date())
                }).then(res=>{
                    console.log(res.data);
                    if(res.data.code===200){
                        this.$message("添加成功")
                    }
                    this.clearForm();
                    this.flushPage()
                })
            }else{  //修改
                this.dialogFormVisible = false;
                this.axios.put("/article/update",{
                    id:this.row.id,
                    articlename: this.form.articlename,
                    articleintroduce: this.form.articleintroduce,
                    teacherId: this.form.teacherId,
                    tabularchart: this.form.tabularchart,  //图片
                    details: this.form.details,   //详情
                    typeId: this.form.typeId,
                }).then(res=>{
                    // console.log("-------teacherId---------")
                    console.log(res.data)
                    if(res.data.code===200){
                        this.$message("修改成功")
                    }
                    this.flushPage()
                })
            }
        },
        //新增文章
        addXiaoqu() {
            this.dialogTitle = "新增文章";
            this.dialogFormVisible = true;
            this.allId = -1;
            this.clearForm();
        },
        //保存后清空表单
        clearForm() {
            this.form.articlename="",
            this.form.articleintroduce="",
            this.form.teacherId="",
            this.uploadImageList = [];
            this.form.details="",
            this.form.typeId=""
        },
        //格式化时间
        formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        //取消
        cancel() {
            this.dialogFormVisible = false;
        },
        //编辑
        editClick(row) {
            console.log(row)
            this.dialogTitle = "编辑文章";
            this.dialogFormVisible = true;
            this.row = row;
            this.allId = this.row.id;
            console.log(this.allId);

            // this.form = { ...row };  // 使用解构赋值复制整个对象

            // 图片回显
            if (row.tabularchart) {
                this.uploadImageList = [{
                    name: row.tabularchart,
                    url: `http://localhost:8080/article/download?filename=${row.tabularchart}`
                }];
            } else {
                this.uploadImageList = [];
            }

            this.form.articlename=this.row.articlename;
            this.form.articleintroduce=this.row.articleintroduce;
            this.form.teacherId=this.row.teacherId;
            this.form.tabularchart=this.row.tabularchart;
            this.form.details=this.row.details;
            this.form.typeId=this.row.typeId;
        },

        //刷新页面
        flushPage() {

            this.axios.get("/article/findAllArticle",
                {
                    params: {
                        //传输的参数
                        // startTime: "",
                        // endTime: "",
                        pageNum: 1,
                        pageSize: 10,
                    }
                }).then((res) => {
                console.log(res.data.data.list)
                this.tableData = res.data.data.list;
                //页面加载时添加总数量
                this.page.total = res.data.data.total;
            }).catch(err => {
                console.log(err);
            })
        },
        //删除
        deleteClick(index) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log(index)
                this.axios.delete("/article/delete", {
                    params:{
                        id: index
                    }
                }).then((res) => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.flushPage();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //搜索
        searchClick() {
            this.axios.get('/article/findAllByLike',
                {
                    params: {
                        //传输的参数
                        typeName: this.searchContent.typeName === undefined ? '' : this.searchContent.typeName,
                        articlename: this.searchContent.articlename === undefined ? '' : this.searchContent.articlename,
                        pageNum: this.searchContent.pageNum === undefined ? '' : this.searchContent.pageNum,
                        pageSize: this.searchContent.pageSize === undefined ? '' : this.searchContent.pageSize,
                        startTime: this.searchContent.time[0] === undefined ? '' : this.formatDateTime(this.searchContent.time[0]),
                        endTime: this.searchContent.time[1] === undefined ? '' : this.formatDateTime(this.searchContent.time[1]),
                    }
                }
            ).then((res) => {
                //处理响应数据
                console.log(res);
                //真正需要的数据
                console.log(res.data.data.list);
                //将得到的数据加载到tableData
                this.tableData = res.data.data.list;
                this.page.total=res.data.data.total;
            }).catch(err => {
            })
        },
        // 上传
        handleRemove(file) {
            this.uploadImageList = this.uploadImageList.filter(item => item.name !== file.name);
            if (this.uploadImageList.length === 0) {
                this.form.tabularchart = '';
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleDownload(file) {
            console.log(file);
        },

        uploadImg(response, file, fileList) {
            if (response.code === 200) {
                this.form.tabularchart = response.data;
                //解决图片闪动问题
                this.uploadImageList = fileList;

                // this.uploadImageList = fileList.map(file => ({
                //     name: file.name,
                //     url: file.url || `http://localhost:8080/article/download?filename=${file.response.data}`
                // }));
            } else {
                this.$message.error('上传失败');
            }
        },

        //分页函数
        //点击按钮切换页面
        handleCurrentChange(currentPage) {
            this.page.currentPage = currentPage; //每次点击分页按钮，当前页发生变化
            console.log("页码切换：" + this.page.currentPage);          // 获取改变页码后的数据
            this.axios.get('/article/findAllArticle',
                {
                    params: {
                        //传输的参数
                        pageNum: this.page.currentPage,
                        pageSize: this.page.pageSize,
                    }
                }
            ).then((res) => {
                //更新表格数据
                this.tableData = res.data.data.list;
                console.log(this.tableData)
                //设置total
                this.page.total = res.data.data.total
                console.log(this.page.total)
            }).catch(err => {
                console.log(err)
            });
        },

        //富文本所需方法
        onEditorBlur() {
            //失去焦点事件
        },
        onEditorFocus() {
            //获得焦点事件
        },
        onEditorChange() {
            //内容改变事件
        },
    }
}
</script>

<template>
    <div class="xiaoqu">
        <div class="xiaoqu-content">
            <div class="searchBox">
                <div class="searchLi">
                    <span class="xiaoquName">文章名：</span>
                    <input type="text" autocomplete="off" v-model="searchContent.articlename">
                </div>
                <div class="searchLi">
                    <span class="xiaoquName">所属类型：</span>
                    <input type="text" autocomplete="off" v-model="searchContent.typeName">
                </div>
                <div class="searchLi">
                    <span>创建时间：</span>
                    <el-date-picker
                        v-model="searchContent.time"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </div>
                <div class="searchBtn">
                    <el-button type="primary" @click="searchClick">搜索</el-button>
                </div>
            </div>
            <div class="addXiaoquBtn">
                <el-button type="text" @click="addXiaoqu" class="addBtn">新增文章</el-button>
                <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="80%">
                    <el-form :model="form">
                        <el-form-item label="文章名称" :label-width="formLabelWidth">
                            <el-input v-model="form.articlename" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="文章简介" :label-width="formLabelWidth">
                            <el-input v-model="form.articleintroduce" autocomplete="off"></el-input>
                        </el-form-item>

                        <!-- 咨询师-->
                        <el-form-item label="关联咨询师" :label-width="formLabelWidth">
                            <el-select v-model="form.teacherId" placeholder="请选择">
                                <el-option
                                    v-for="(v,i) in teachers"
                                    :key="i"
                                    :label="v.name"
                                    :value="v.id">{{v.name}}
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="图片" :label-width="formLabelWidth" style="text-align: left;">
                            <!-- <el-input v-model="form.img"></el-input> -->
                            <!-- name="file" 后端参数名跟这个name要保持一致 默认名是file-->
                            <el-upload
                                v-if="dialogFormVisible"
                                name="file"
                                action="http://localhost:8080/article/upload"
                                list-type="picture-card"
                                :file-list="uploadImageList"
                                :auto-upload="true"
                                :on-success="uploadImg">
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{ file }">
                                    <img
                                        class="el-upload-list__item-thumbnail"
                                        :src="file.url"
                                        alt=""/>
                                    <span class="el-upload-list__item-actions">
                                    <span
                                        class="el-upload-list__item-preview"
                                        @click="handlePictureCardPreview(file)">
                                      <i class="el-icon-zoom-in"></i>
                                    </span>
                                    <span
                                        v-if="!disabled"
                                        class="el-upload-list__item-delete"
                                        @click="handleDownload(file)">
                                      <i class="el-icon-download"></i>
                                    </span>
                                    <span
                                        v-if="!disabled"
                                        class="el-upload-list__item-delete"
                                        @click="handleRemove(file)">
                                      <i class="el-icon-delete"></i>
                                    </span>
                                  </span>
                                </div>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt=""/>
                            </el-dialog>
                        </el-form-item>

                        <!-- 类型-->
                        <el-form-item label="所属类型" :label-width="formLabelWidth">
                            <el-select v-model="form.typeId" placeholder="请选择">
                                <el-option
                                    v-for="(v,i) in types"
                                    :key="i"
                                    :label="v.name"
                                    :value="v.id">{{v.name}}
                                </el-option>
                            </el-select>
                        </el-form-item>


                        <el-form-item label="详情内容" :label-width="formLabelWidth">
                            <quill-editor class="editor" v-model="form.details" ref="myQuillEditor" :options="editorOption"
                                          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
                                          @change="onEditorChange($event)" style="height: 300px">
                            </quill-editor>
                        </el-form-item>

                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="cancel">取 消</el-button>
                        <el-button @click="save">保 存</el-button>
                    </div>
                </el-dialog>
            </div>
            <div class="xiaoqu-table">
                <el-table
                    :data="tableData"
                    border
                    :cell-style="{'text-align':'center'}"
                    :header-cell-style="{background: '#1890ff',color: '#ffffff','text-align': 'center'}">
                    <el-table-column
                        prop="id"
                        label="Id">
                    </el-table-column>
                    <el-table-column
                        prop="articlename"
                        label="文章名称">
                    </el-table-column>
                    <el-table-column
                        prop="articleintroduce"
                        label="文章简介">
                    </el-table-column>
                    <el-table-column
                        prop="teacherName"
                        label="关联咨询师">
                    </el-table-column>

                    <el-table-column label="图片">
                        <!-- <img :src="'http://localhost:8080/jingxuan/down?filename='+img"/> -->
                        <template slot-scope="scope">
                            <el-image
                                style="width: 100px; height: 100px"
                                :src="'http://localhost:8080/article/download?filename='+scope.row.tabularchart"
                                fit="fill">
                            </el-image>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="typeName"
                        label="所属类型">
                    </el-table-column>
                    <el-table-column
                        prop="createtime"
                        label="创建时间">
                    </el-table-column>
                    <el-table-column
                        label="操作">
                        <template slot-scope="scope">
                            <el-button @click="editClick(scope.row)" type="text" size="small">编辑文章</el-button>
                            <el-button @click="deleteClick(scope.row.id)" type="text" size="small">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!--分页按钮-->
            <div class="block">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page.sync="page.pageNum"
                    :page-size="10"
                    layout="prev, pager, next,jumper, ->, total"
                    :total="page.total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<style scoped>
.xiaoqu {
    height: 800px;
    /*background-color: hotpink;*/
}

.xiaoqu-content {
    padding: 20px;
}

.searchBox {
    display: flex;
    justify-content: flex-start;
}

.searchLi {
    margin-right: 20px;
}

.addXiaoquBtn {
    margin-top: 20px;
}

input {
    height: 34px;
    outline: none;
    border: 1px solid #aaa;
    padding: 0 15px;
    border-radius: 5px;
}

input:hover {
    border: 1px solid #555555;
}

input:focus {
    border: 1px solid #409eff;
}

.addBtn {
    padding: 10px 20px;
    background-color: #409eff;
    color: whitesmoke;
    border: 1px solid #409eff;
}

.xiaoqu-table {
    margin-top: 20px;
    table-layout: auto;
}
.dialog-footer{
    margin-top: 40px;
}
</style>